#include <PubSubClient.h>
#include <ArduinoJson.h>
#include <WiFi.h>
#include "mqtt.h"
WiFiClient espClient;
PubSubClient client(espClient);
const char *client_id = "esp32-client";
const char *serverTopic = "";
const char *id = "";
float temperature;
float humidity;
float light_magnitude;
float h2s;

void connect_mqtt(const char *device_id, const char *mqtt_broker, const char *topic, const char *mqtt_username, const char *mqtt_password, const int mqtt_port) {
    serverTopic = topic;
    id = device_id;
    client.setServer(mqtt_broker, mqtt_port);
    client.setCallback(callback);
    while (!client.connected()) {
        String id = String(client_id + WiFi.macAddress());
        Serial.printf("客户端%s正在连接%s\n", client_id, mqtt_broker);
        if (client.connect(id.c_str(), mqtt_username, mqtt_password)) {
            Serial.println("MQTT连接成功！");
        } else {
            Serial.print("连接失败：");
            Serial.println(client.getWriteError());
            delay(2000);
        }
    }
    
}

void subscribe(const char *topic) {
    client.subscribe(topic);
}

void publish() {
    String payload;
    JsonDocument data;
    data["temperature"] = temperature;
    data["humidity"] = humidity;
    data["device_id"] = id;
    data["light_magnitude"] = light_magnitude;
    data["h2s"] = h2s;
    serializeJson(data, payload);
    client.publish(serverTopic, payload.c_str());
}

void set_temperature(float tem) {
    temperature = tem;
}

void set_humidity(float hum) {
    humidity = hum;
}

void set_light_magnitude(float light) {
    light_magnitude = light;
}

void set_h2s(float num) {
    h2s = num;
}

void callback(char *topic, byte *payload, unsigned int length) {
    String message = String();
    for (int i = 0; i < length; i++) {
        message += (char) payload[i];
    }
    Serial.printf("主题：%s，消息：%s", topic, message);
}